/**
 * Created by gaojian on 15/9/7.
 */
var express = require('express'),
    bodyParser = require('body-parser'),
    pool = require('./pool'),
    router = express.Router(),
    marked = require( "marked" ),
    _ = require('lodash'),
    moment = require('moment');


marked.setOptions({
    renderer: new marked.Renderer(),
    gfm: true,
    tables: true,
    breaks: true,
    pedantic: false,
    sanitize: true,
    smartLists: true,
    smartypants: true,
    highlight: function (code) {
        return require('highlight.js').highlightAuto(code).value;
    }
});

router.get('/home',function(req,res,next){
    pool.getConnection(function(error,connect){
        var total = 0,tag;
        connect.query('select count(*) from article',function(err1,result){
            total = _.values(result[0])[0];
        });

        connect.query('select * from tag order by id desc',function(err2,rows){
            tag = rows;
        });

        connect.query('select * from article order by id desc limit '+(req.query.cur_page-1)*req.query.page_size+','+req.query.page_size +'',function(err,rows){
                res.json({
                    "code":200,
                    "msg":"success",
                    "data": {
                        "list": _.each(rows,function(item){
                            item.add_time = moment(item.add_time).format('YYYY-MM-DD HH:mm:ss');
                            if(!item.tag){
                                return item;
                            }
                            var arr = item.tag.split(',');
                            item.tag = _.map(arr,function(tid){
                                return _.find(tag,function(foo){
                                    return foo.id == tid;
                                });
                            });
                            return item;
                        }),
                        "total":total,
                        "cur_page":parseInt(req.query.cur_page,10),
                        "page_size":parseInt(req.query.page_size,10)
                    },
                    tag:tag
                });

            connect.release();
        });
    })
});

router.get('/tag',function(req,res,next){
   pool.getConnection(function(error,connect){
       connect.query('select * from tag order by id desc',function(err,rows){
           res.json({
               "code":200,
               "msg":"success",
               "data":rows
           });
           connect.release();
       })
   });
});

router.post('/tag/add',function(req,res,next){
    pool.getConnection(function(error,connect){
        connect.query('insert into tag(name) values("'+req.body.name+'")',function(err,rows){
            res.json({
                "code":200,
                "msg":"success",
                "data":{id:rows.insertId,name:req.body.name}
            });
            connect.release();
        })
    });
});

router.post('/tag/modify',function(req,res,next){
    pool.getConnection(function(error,connect){
        connect.query('update tag set name="'+req.body.name+'" where id="'+req.body.id+'"',function(err,rows){
            res.json({
                "code":200,
                "msg":"success",
                "data":null
            });
            connect.release();
        })
    });
});

router.get('/tag/:id',function(req,res,next){
    pool.getConnection(function(error,connect){
        var total = 0;
        connect.query('select count(*) from article where tag REGEXP "'+req.params.id+'"',function(err1,result){
            total = _.values(result[0])[0];
        });

        connect.query('select id,name from tag',function(err2,rows){
            tag = rows;
            connect.query('select * from article where tag REGEXP "'+req.params.id+'" order by id desc limit '+(req.query.cur_page-1)*req.query.page_size+','+req.query.page_size,function(err,rows){
                res.json({
                    "code":200,
                    "msg":"success",
                    "data": {
                        "list": _.each(rows,function(item){
                            item.add_time = moment(item.add_time).format('YYYY-MM-DD HH:mm:ss');
                            if(!item.tag){
                                return item;
                            }
                            var arr = item.tag.split(',');
                            item.tag = _.map(arr,function(tid){
                                return _.find(tag,function(foo){
                                    return foo.id == tid;
                                });
                            });
                            return item;
                        }),
                        "total":total,
                        "cur_page":parseInt(req.query.cur_page,10),
                        "page_size":parseInt(req.query.page_size,10),
                        "cur_tag": _.result(_.find(tag,function(item){
                            return item.id == req.params.id;
                        }),'name')
                    }
                });
                connect.release();
            });
        });
    })
});

router.get('/article/:id',function(req,res,next){

    pool.getConnection(function(error,connect){
        connect.query('select id,name from tag',function(err2,rows){
            tag = rows;
        });

        connect.query('select * from article where article.id="'+req.params.id+'"',function(err,rows){
            res.json({
                "code":200,
                "msg":"success",
                "data": _.each(rows,function(item){
                    item.add_time = moment(item.add_time).format('YYYY-MM-DD HH:mm:ss');
                    if(!item.tag){
                        return item;
                        connect.release();
                    }
                    var arr = item.tag.split(',');
                    item.tag = _.map(arr,function(tid){
                        return _.find(tag,function(foo){
                            return foo.id == tid;
                        });
                    });
                    return item;
                })
            });
            connect.release();
        });
    })
});

router.get('/article/modify/:id',function(req,res,next){

    pool.getConnection(function(error,connect){
        connect.query('select id,name from tag',function(err2,rows){
            tag = rows;
        });

        connect.query('select * from article where article.id="'+req.params.id+'"',function(err,rows){
            res.json({
                "code":200,
                "msg":"success",
                "data": _.each(rows,function(item){
                    item.add_time = moment(item.add_time).format('YYYY-MM-DD HH:mm:ss');
                    if(!item.tag){
                        return item;
                        connect.release();
                    }
                    var arr = item.tag.split(',');
                    item.tag_name = _.map(arr,function(tid){
                        return _.result(_.find(tag,function(foo){
                            return foo.id == tid;
                        }),'name');
                    });
                    return item;
                })
            });
            connect.release();
        });
    })
});

router.post('/add',function(req,res,next){
    if(req.query.pass == ''){
        res.json({
            "code":400,
            "msg":"通行码不得为空",
            "data":null
        });
        return;
    }
    pool.getConnection(function(error,connect){
        connect.query('select * from user where pass="'+req.body.pass+'"',function(err,rows){
            if(rows.length){
                next();
            }else{
                res.json({
                    "code":400,
                    "msg":"通行码不正确",
                    "data":null
                });
                connect.release();
                return;
            }
            connect.release();
        })
    });

},function(req,res,next){
   if(req.body.title == '' || req.body.digest == '' || req.body.tag == '' || req.body.pass == '' || req.body.content == ''){
       res.json({
           "code":400,
           "msg":"参数不得为空",
           "data":null
       });
       return;
   }
    next();
},function(req,res,next){
    pool.getConnection(function(error,connect){
        connect.query('insert into article(title,digest,content,tag,add_time) values("'+req.body.title+'","'+req.body.digest+'","'+req.body.content+'","'+req.body.tag+'",SYSDATE())',function(err,rows){
            if(rows){
                res.json({
                    "code":200,
                    "msg":"success",
                    "data":null
                });
            }else{
                res.json({
                    "code":400,
                    "msg":"数据库插入异常",
                    "data":null
                });
            }
            connect.release();
        })
    })
});

router.post('/article/modify',function(req,res,next){
    if(req.query.pass == ''){
        res.json({
            "code":400,
            "msg":"通行码不得为空",
            "data":null
        });
        return;
    }
    pool.getConnection(function(error,connect){
        connect.query('select * from user where pass="'+req.body.pass+'"',function(err,rows){
            if(rows.length){
                next();
            }else{
                res.json({
                    "code":400,
                    "msg":"通行码不正确",
                    "data":null
                });
                connect.release();
                return;
            }
            connect.release();
        })
    });

},function(req,res,next){
    if(req.body.title == '' || req.body.digest == '' || req.body.tag == '' || req.body.pass == '' || req.body.content == ''){
        res.json({
            "code":400,
            "msg":"参数不得为空",
            "data":null
        });
        return;
    }
    next();
},function(req,res,next){
    pool.getConnection(function(error,connect){
        connect.query('update article set title="'+req.body.title+'" and digest="'+req.body.digest+'" and content="'+req.body.content+'" and tag="'+req.body.tag+'" and modify_time=SYSDATE() where id="'+req.body.id+'"',function(err,rows){
            if(rows){
                res.json({
                    "code":200,
                    "msg":"success",
                    "data":null
                });
            }else{
                res.json({
                    "code":400,
                    "msg":"数据库插入异常",
                    "data":null
                });
            }
            connect.release();
        })
    })
});

router.post('/article/delete',function(req,res,next){
    pool.getConnection(function(error,connect){
        connect.query('delete from article where id="'+req.body.id+'"',function(err,rows){
            if(rows.affectedRows){
                res.json({
                    "code":200,
                    "msg":"success",
                    "data":null
                });
            }else{
                res.json({
                    "code":400,
                    "msg":"删除失败",
                    "data":null
                });
            }
            connect.release();
        })
    });
});

module.exports = router;